/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制
 */
package com.avic.modules.system.rest;

import com.avic.dozer.service.IGenerator;
import com.avic.exception.BadRequestException;
import com.avic.modules.log.domain.vo.LogEnumeration;
import com.avic.modules.log.domain.vo.LogVo;
import com.avic.modules.log.service.LogsService;
import com.avic.modules.log.utils.ContrastObjUtil;
import com.avic.modules.system.domain.Dept;
import com.avic.modules.system.domain.Job;
import com.avic.modules.system.domain.vo.JobVo;
import com.avic.modules.system.service.JobService;
import com.avic.modules.system.service.dto.JobDto;
import com.avic.modules.system.service.dto.JobQueryCriteria;
import com.avic.modules.system.service.mapper.DeptMapper;
import com.avic.modules.system.service.mapper.JobMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author zhangzikang
 * @date 2022-08-14
 */
@Api(tags = "系统：岗位管理")
@RestController
@RequestMapping("/api/job")
public class JobController {

    private final JobService jobService;

    private final JobMapper jobMapper;

    private final DeptMapper deptMapper;

    private final LogsService logsService;

    private final IGenerator generator;

    private static final String ENTITY_NAME = "job";

    public JobController(JobService jobService, JobMapper jobMapper, DeptMapper deptMapper, LogsService logsService, IGenerator generator) {
        this.jobService = jobService;
        this.jobMapper = jobMapper;
        this.logsService = logsService;
        this.generator = generator;
        this.deptMapper = deptMapper;
    }

    @ApiOperation("导出岗位数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('admin','job:download')")
    public void download(HttpServletResponse response, JobQueryCriteria criteria,Pageable pageable) throws IOException {
        jobService.download(generator.convert(jobService.queryAlls(criteria,pageable), JobDto.class), response);
    }

    @ApiOperation("查询岗位")
    @GetMapping
    @PreAuthorize("@el.check('admin','job:list','user:list')")
    public ResponseEntity<Object> getJobs(JobQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(jobService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @ApiOperation("新增岗位")
    @PostMapping
    @PreAuthorize("@el.check('admin','job:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Job resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }

        Long id = resources.getDept().getId();
        QueryWrapper<Job> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id",id);
        wrapper.eq("name",resources.getName());
        List<Job> jobs = jobMapper.selectList(wrapper);
        if(jobs.size()>0){
            throw new BadRequestException("相同部门下不能有重复岗位");
        }

        // 创建操作日志
        String name = "[添加]了"+ " [" + resources.getName()+ "] " +"岗位信息";
        LogVo logVo = new LogVo();
        logVo.setAction(LogEnumeration.Add_TO.getMessage());
        logVo.setBehavior(name);
        logsService.save(logVo);

        // 添加岗位信息
        resources.setDeptId(resources.getDept().getId());
        return new ResponseEntity<>(jobService.save(resources), HttpStatus.CREATED);
    }

    @ApiOperation("修改岗位")
    @PutMapping
    @PreAuthorize("@el.check('admin','job:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Job resources) {

        Long id = resources.getDept().getId();
        QueryWrapper<Job> wrapper = new QueryWrapper<>();
        wrapper.eq("dept_id",id);
        wrapper.eq("name",resources.getName());
        List<Job> jobs = jobMapper.selectList(wrapper);
        boolean whether = false;
        for(Job job:jobs){
            if(job.getId() != resources.getId()){
                whether = true;
                break;
            }
        }
        if(jobs.size()>0 && whether){
            throw new BadRequestException("相同部门下不能有重复岗位");
        }

        // 修改前
        Job job = jobMapper.selectById(resources.getId());
        Dept dept = deptMapper.selectById(job.getDeptId());
        JobVo jobDto = new JobVo();
        jobDto.setDeptName(dept!=null?dept.getName():null);
        jobDto.setName(job.getName());
        jobDto.setSort(job.getSort());
        Boolean enabled = job.getEnabled();
        if(enabled){
            jobDto.setType("开启");
        } else {
            jobDto.setType("禁用");
        }

        // 修改后
        JobVo jobDto2 = new JobVo();
        Dept dept2 = deptMapper.selectById(resources.getDept()!=null?resources.getDept().getId():null);
        jobDto2.setDeptName(dept2!=null?dept2.getName():null);
        jobDto2.setName(resources.getName());
        jobDto2.setSort(resources.getSort());
        Boolean enabled2 = resources.getEnabled();
        if(enabled2){
            jobDto2.setType("开启");
        } else {
            jobDto2.setType("禁用");
        }

        // 创建操作日志
        String s = ContrastObjUtil.comparObj(jobDto2,jobDto);
        String name = "[修改]了"+ " [" + job.getName() + "] " +"岗位信息";
        LogVo logVo = new LogVo();
        logVo.setInformation(s);
        logVo.setAction(LogEnumeration.MODIFY.getMessage());
        logVo.setBehavior(name);
        logsService.save(logVo);

        // 修改岗位信息
        resources.setDeptId(resources.getDept().getId());
        jobService.saveOrUpdate(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("删除岗位")
    @DeleteMapping
    @PreAuthorize("@el.check('admin','job:del')")
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {

        try {
            // 查看删除了哪些部门
            List<String> js = new ArrayList<>();
            for(Long job:ids){
                Job dept1 = jobMapper.selectById(job);
                js.add(dept1.getName());
            }
            // 创建操作日志
            String name = "[删除]了"+ js.toString() + "岗位信息";
            LogVo logVo = new LogVo();
            logVo.setAction(LogEnumeration.Delete.getMessage());
            logVo.setBehavior(name);
            logsService.save(logVo);

            // 删除部门
            jobService.removeByIds(ids);
        } catch (Throwable e) {
            throw new BadRequestException("所选岗位存在用户关联，请取消关联后再试");
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
